package io.renren.mp;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import io.renren.mp.config.MybatisPlusConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.StringPool.COMMA;

/**
 * @author jerry
 * @date 2019/9/6 16:41
 */
@Slf4j
@Component
public class MybatisPlusGenerator {

    private static final String DATETIME = "datetime";
    @Autowired
    private MybatisPlusConfig mybatisPlusConfig;
    @Autowired
    private DruidDataSource dataSource;

    public void generate(String tables, String projectPath) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        GlobalConfig gc = getGlobalConfig(projectPath);
        mpg.setGlobalConfig(gc);
        mpg.setDataSource(getDataSourceConfig());

        PackageConfig pc = getPackageConfig();
        mpg.setPackageInfo(pc);

        InjectionConfig cfg = getInjectionConfig(projectPath);
        mpg.setCfg(cfg);
        TemplateConfig templateConfig = getTemplateConfig();
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = getStrategyConfig(tables);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    private PackageConfig getPackageConfig() {
        // 包配置
        String packageName = mybatisPlusConfig.getPackageName();
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        return pc;
    }

    private GlobalConfig getGlobalConfig(String projectPath) {
        String author = mybatisPlusConfig.getAuthor();
        if (StringUtils.isEmpty(projectPath)) {
            projectPath = System.getProperty("user.dir");
        }
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        // 是否覆盖文件
        gc.setFileOverride(true);
        // xml resultmap
        gc.setBaseResultMap(true);
        // xml columlist
        gc.setBaseColumnList(true);
        // 实体属性 Swagger2 注解
        gc.setSwagger2(true);
        return gc;
    }

    private DataSourceConfig getDataSourceConfig() {
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dataSource.getUrl());
        // dsc.setSchemaName("public");
        dsc.setDriverName(dataSource.getDriverClassName());
        dsc.setUsername(dataSource.getUsername());
        dsc.setPassword(dataSource.getPassword());
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                if (fieldType.toLowerCase().contains(DATETIME)) {
                    return DbColumnType.DATE;
                }
                return super.processTypeConvert(globalConfig, fieldType);
            }

        });
        return dsc;
    }

    private InjectionConfig getInjectionConfig(String projectPath) {
        if (StringUtils.isEmpty(projectPath)) {
            projectPath = System.getProperty("user.dir");
        }
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = mybatisPlusConfig.getTemplatePath();
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mp/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        String finalProjectPath = projectPath;
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return finalProjectPath + "/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    private static TemplateConfig getTemplateConfig() {
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        return templateConfig;
    }

    /**
     * @param tables "表名，多个英文逗号分割"
     */
    private static StrategyConfig getStrategyConfig(String tables) {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        // 公共父类
//        strategy.setSuperControllerClass("com.dacheng.info.bim.business.base");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        if (StringUtils.isEmpty(tables)) {
            throw new RuntimeException("请输入表名（多表逗号分隔）");
        }
        String[] tableNames = StringUtils.split(tables, COMMA);
        strategy.setInclude(tableNames);
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("t_");
        return strategy;
    }
}
